import {config,TOKEN_PRE} from '@/service/request/config'
import {UserModel} from '@/service/model/user.js'
import {userStore} from '@/stores/user'
export const uploadImgHook=(emitName,url,filePath='')=>{
	const userModel=new UserModel()
	if(filePath){
		uni.showLoading({
			title:'上传中...'
		})
		const uploadTask = uni.uploadFile({
			url: config.base_url + url,
			filePath: filePath,
			name: 'file', //类型为文件
			// #ifdef H5
			header:{
				"authorization": TOKEN_PRE+uni.getStorageSync('token')
			},
			// #endif
			// #ifdef MP-WEIXIN
			header:{
				"authorization": TOKEN_PRE+uni.getStorageSync('token')
			},
			// #endif
			success: async function(uploadFileRes) {
				const {data,success} = JSON.parse(uploadFileRes.data);
				if(success){
					uni.hideLoading();
					uni.showToast({
						title:'上传成功'
					})
					uni.$emit(emitName,data)
				}else{
					uni.hideLoading();
					uni.showToast({
						title:data.msg || '上传失败',
						icon: 'error',
					})
					uni.$emit(emitName,false)
				}
			}
		});
	}else{
		uni.chooseImage({
			count: 1, 
			sizeType: ['original', 'compressed'],
			success: res => {
				let that = this;
				let file = res.tempFiles[0];
				let filePath = res.tempFilePaths[0];
				uni.showLoading({
					title:'上传中...'
				})
				const uploadTask = uni.uploadFile({
					url: config.base_url + url,
					filePath: filePath,
					name: 'file', //类型为文件
					// #ifdef H5
					header:{
						"authorization": TOKEN_PRE+uni.getStorageSync('token')
					},
					// #endif
					// #ifdef MP-WEIXIN
					header:{
						// "content-type" : 'multipart/form-data',
						"authorization": TOKEN_PRE+uni.getStorageSync('token')
					},
					// #endif
					success: async function(uploadFileRes) {
						const {data,success} = JSON.parse(uploadFileRes.data);
						if(success){
							uni.hideLoading();
							uni.showToast({
								title:'上传成功'
							})
							uni.$emit(emitName,data)
						}else{
							uni.hideLoading();
							uni.showToast({
								title:data.msg || '上传失败',
								icon: 'error',
							})
							uni.$emit(emitName,false)
						}
					}
				});
			}
		});
	}
}